//
// Created by fanghr on 18-3-22.
//
#include "../include/cssl2cpp.h"

cssl::cssl(std::string path, cssl_callback_t cb, int id, int baud, int bits, int parity, int stop) {
    serial = cssl_open(path.c_str(), cb, id, baud, bits, parity, stop);
    if (serial == nullptr)throw nullptr;
}

cssl::~cssl() {
    flush();
    close();
}

void cssl::setup(int baud, int bits, int parity, int stop) {
    cssl_setup(serial, baud, bits, parity, stop);
}

void cssl::close() {
    cssl_close(serial);
}

void cssl::flush() {
    cssl_drain(serial);
}

void cssl::start() {
    cssl_start();
}

void cssl::stop() {
    cssl_stop();
}

void cssl::setflowcontrol(int rtscts, int xonxoff) {
    cssl_setflowcontrol(serial, rtscts, xonxoff);
}

void cssl::settimeout(unsigned int timeout) {
    cssl_settimeout(serial, timeout);
}

void cssl::putdata(std::list<uint8_t> &list) {
    for (auto i:list)
        cssl_putchar(serial, i);
}

void cssl::putchar(char ch) {
    cssl_putchar(serial, ch);
}

void cssl::putdata(uint8_t *arr, size_t len) {
    cssl_putdata(serial, arr, static_cast<int>(len));
}

void cssl::putstring(const std::string &str) {
    cssl_putstring(serial, const_cast<char *>(str.c_str()));
}

void cssl::putstring(const char *str) {
    cssl_putstring(serial, const_cast<char *>(str));
}

uint8_t cssl::getchar() {
    return static_cast<uint8_t>(cssl_getchar(serial));
}

int cssl::getdata(uint8_t *buffer, int size) {
    return cssl_getdata(serial, buffer, size);
}

int cssl::get_err() {
    return cssl_geterror();
}

const std::string cssl::get_err_str() {
    return std::string(cssl_geterrormsg());
}

int cssl::getdata(std::list<uint8_t> &buffer, int size) {
    uint8_t tmp[size];
    int real_size = cssl_getdata(serial, tmp, size);
    for (auto i = 0; i < real_size; i++)
        buffer.push_back(tmp[i]);
    return real_size;
}
